package org.credo.thread.control.synchronizedTest;

/**
 * 本代码是Account类提供存钱,取钱2个方法,因为这2个方法可能需要并发修改Account类的balance字段.
 * 所以都是用了synchronized来修饰方法.还是用了wait和notifyall来控制线程的协作.
 */
public class Account {
	private String accountNo;
	private double balance;

	// 没人存钱就为false,能save. 有就是true.
	private boolean haveMoney = false;

	public Account() {

	}

	public Account(String accountNo, double balance) {
		this.accountNo = accountNo;
		this.balance = balance;
	}

	public synchronized void saveMoney(double saveMoney) {
		try {
			if (!haveMoney) {
				// 执行存钱操作
				System.out.println(Thread.currentThread().getName() + "存钱:" + saveMoney);
				balance = +saveMoney;
				System.out.println("账户余额为:" + balance);
				haveMoney = true;
				// 唤醒其他线程
				this.notifyAll();
			} else {
				// 当前线程等待
				this.wait();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public synchronized void getMoney(double getMoney, int i) {
		try {
			System.out.println("i" + i);
			if (haveMoney) {
				// 执行取钱操作
				System.out.println(Thread.currentThread().getName() + "取钱:" + getMoney);
				balance = -getMoney;
				System.out.println("账户余额为:" + balance);
				haveMoney = false;
				// 唤醒其他线程
				this.notifyAll();
			} else {
				this.wait();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String getAccountNo() {
		return accountNo;
	}

	public void setAccountNo(String accountNo) {
		this.accountNo = accountNo;
	}

	public boolean isHaveMoney() {
		return haveMoney;
	}

	public void setHaveMoney(boolean haveMoney) {
		this.haveMoney = haveMoney;
	}

	public double getBalance() {
		return balance;
	}

	@Override
	public int hashCode() {
		return this.accountNo.hashCode();
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj != null && obj.getClass() == Account.class) {
			Account acc = (Account) obj;
			return acc.getAccountNo().equals(accountNo);
		}
		return false;
	}
}
